package com.qianniu.napi.admin.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.EncryptUtil;
import com.qianniu.napi.common.util.HttpUtil;
import com.qianniu.napi.common.util.WeixinUtil;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

@Configuration
@Component // 此注解必加
@EnableScheduling // 此注解必加
public class CdnimageTask {

    private static final Logger logger = LoggerFactory.getLogger(CdnimageTask.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IMerchantAppService merchantAppService;
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IDisplayFenleiService displayFenleiService;

//    @Scheduled(cron = "0 48 * * * ?")
    public void goodstoCdn() {

        Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>()
                .setSqlSelect("id,mcode,mpcode,state,iscdn")
                .eq("iscdn", 1);

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;

        while (flag) {
            Page<MerchantApp> page = merchantAppService.selectPage(new Page<MerchantApp>(index, limit), wrapper);
            for (MerchantApp mapp : page.getRecords()) {

                Wrapper<Goods> uwrapper = new EntityWrapper<Goods>().setSqlSelect("id,thumb,thumbhd,pic,photos,info,packinglist,afterservice,introduction,shareimg,homeurl").eq("mpid", mapp.getId());

                boolean uflag = true;
                Integer uindex = 1;

                while (uflag) {
                    logger.info("==============================goodstoCdn 3333");

                    Page<Goods> upage = goodsService.selectPage(new Page<Goods>(uindex, limit), uwrapper);
                    for (Goods uitem : upage.getRecords()) {
                        logger.info("==============================goodstoCdn 4444");
                        Boolean ug = false;
//                        thumb,thumbhd,
                        if (!Strings.isNullOrEmpty(uitem.getThumb()) && uitem.getThumb().indexOf("//imgcdn.") < 0) {
                            uitem.setThumb(uitem.getThumb().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!Strings.isNullOrEmpty(uitem.getThumbhd())&& uitem.getThumbhd().indexOf("//imgcdn.") < 0) {
                            uitem.setThumbhd(uitem.getThumbhd().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

//                        pic,photos
                        if (!Strings.isNullOrEmpty(uitem.getPic()) && uitem.getPic().indexOf("//imgcdn.") <0) {
                            uitem.setPic(uitem.getPic().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!Strings.isNullOrEmpty(uitem.getPhotos())) {
                            uitem.setPhotos(uitem.getPhotos().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

//                        info,packinglist,afterservice,introduction,
                        if (!Strings.isNullOrEmpty(uitem.getInfo())) {
                            uitem.setInfo(uitem.getInfo().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        if (!Strings.isNullOrEmpty(uitem.getPackinglist())) {
                            uitem.setPackinglist(uitem.getPackinglist().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        if (!Strings.isNullOrEmpty(uitem.getAfterservice())) {
                            uitem.setAfterservice(uitem.getAfterservice().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        if (!Strings.isNullOrEmpty(uitem.getIntroduction())) {
                            uitem.setIntroduction(uitem.getIntroduction().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

//                        shareimg,homeurl
                        if (!Strings.isNullOrEmpty(uitem.getShareimg()) && uitem.getShareimg().indexOf("//imgcdn.") <0) {
                            uitem.setShareimg(uitem.getShareimg().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        if (!Strings.isNullOrEmpty(uitem.getHomeurl()) && uitem.getHomeurl().indexOf("//imgcdn.") <0) {
                            uitem.setHomeurl(uitem.getHomeurl().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!ug) continue;

                        uitem.updateById();
                        logger.info("==============================goodstoCdn uitem.updateById() ok uindex=" + uindex);
                    }
                    uflag = upage != null && upage.getRecords().size() == limit;
                    uindex++;
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========goodstoCdn flag=" + flag);
            logger.info("==========goodstoCdn index=" + index);
        }
    }

//    @Scheduled(cron = "0 48 18 * * ?")
    public void newstoCdn() {

        Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>()
                .setSqlSelect("id,mcode,mpcode,state,iscdn")
                .eq("iscdn", 1);

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;

        while (flag) {
            Page<MerchantApp> page = merchantAppService.selectPage(new Page<MerchantApp>(index, limit), wrapper);
            for (MerchantApp mapp : page.getRecords()) {

                Wrapper<News> uwrapper = new EntityWrapper<News>().setSqlSelect("id,pic,photos,info").eq("mpid", mapp.getId());

                boolean uflag = true;
                Integer uindex = 1;

                while (uflag) {
                    logger.info("==============================newstoCdn 3333");

                    Page<News> upage = newsService.selectPage(new Page<News>(uindex, limit), uwrapper);
                    for (News uitem : upage.getRecords()) {
                        logger.info("==============================newstoCdn 4444");
                        Boolean ug = false;

                        if (!Strings.isNullOrEmpty(uitem.getPic()) && uitem.getPic().indexOf("//imgcdn.") <0) {
                            uitem.setPic(uitem.getPic().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!Strings.isNullOrEmpty(uitem.getPhotos())) {
                            uitem.setPhotos(uitem.getPhotos().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!Strings.isNullOrEmpty(uitem.getInfo())) {
                            uitem.setInfo(uitem.getInfo().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!ug) continue;

                        uitem.updateById();
                        logger.info("==============================newstoCdn uitem.updateById() ok uindex=" + uindex);
                    }
                    uflag = upage != null && upage.getRecords().size() == limit;
                    uindex++;
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========newstoCdn flag=" + flag);
            logger.info("==========newstoCdn index=" + index);
        }
    }


//    @Scheduled(cron = "0 48 18 * * ?")
    public void displayFenleitoCdn() {

        Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>()
                .setSqlSelect("id,mcode,mpcode,state,iscdn")
                .eq("iscdn", 1);

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;

        while (flag) {
            Page<MerchantApp> page = merchantAppService.selectPage(new Page<MerchantApp>(index, limit), wrapper);
            for (MerchantApp mapp : page.getRecords()) {

                Wrapper<DisplayFenlei> uwrapper = new EntityWrapper<DisplayFenlei>()
                        .setSqlSelect("id,pic").eq("mpid", mapp.getId());

                boolean uflag = true;
                Integer uindex = 1;

                while (uflag) {
                    logger.info("==============================displayFenleitoCdn 3333");

                    Page<DisplayFenlei> upage = displayFenleiService
                            .selectPage(new Page<DisplayFenlei>(uindex, limit), uwrapper);

                    for (DisplayFenlei uitem : upage.getRecords()) {
                        logger.info("==============================displayFenleitoCdn 4444");
                        Boolean ug = false;

                        if (!Strings.isNullOrEmpty(uitem.getPic()) && uitem.getPic().indexOf("//imgcdn.") <0) {
                            uitem.setPic(uitem.getPic().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!ug) continue;

                        uitem.updateById();
                        logger.info("==============================displayFenleitoCdn uitem.updateById() ok uindex=" + uindex);
                    }
                    uflag = upage != null && upage.getRecords().size() == limit;
                    uindex++;
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========displayFenleitoCdn flag=" + flag);
            logger.info("==========displayFenleitoCdn index=" + index);
        }
    }


//    @Scheduled(cron = "0 45 18 * * ?")
    public void storestoCdn() {

        Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>()
                .setSqlSelect("id,mcode,mpcode,state,iscdn")
                .eq("iscdn", 1);

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;

        while (flag) {
            Page<MerchantApp> page = merchantAppService.selectPage(new Page<MerchantApp>(index, limit), wrapper);
            for (MerchantApp mapp : page.getRecords()) {

                Wrapper<Store> uwrapper = new EntityWrapper<Store>()
                        .setSqlSelect("id,thumb,info,logo,zhizhao,pic,photos,xiangqing,xukezheng")
                        .eq("mpid", mapp.getId());

                boolean uflag = true;
                Integer uindex = 1;

                while (uflag) {
                    logger.info("==============================storestoCdn 3333");

                    Page<Store> upage = storeService.selectPage(new Page<Store>(uindex, limit), uwrapper);
                    for (Store uitem : upage.getRecords()) {
                        logger.info("==============================storestoCdn 4444");
                        Boolean ug = false;

//                       pic,photos,
                        if (!Strings.isNullOrEmpty(uitem.getPic()) && uitem.getPic().indexOf("//imgcdn.") <0) {
                            uitem.setPic(uitem.getPic().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!Strings.isNullOrEmpty(uitem.getPhotos())) {
                            uitem.setPhotos(uitem.getPhotos().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

//                        thumb,info,logo
                        if (!Strings.isNullOrEmpty(uitem.getThumb()) && uitem.getThumb().indexOf("//imgcdn.") <0) {
                            uitem.setThumb(uitem.getThumb().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        if (!Strings.isNullOrEmpty(uitem.getLogo()) && uitem.getLogo().indexOf("//imgcdn.") <0) {
                            uitem.setLogo(uitem.getLogo().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        if (!Strings.isNullOrEmpty(uitem.getInfo())) {
                            uitem.setInfo(uitem.getInfo().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        //,zhizhao,,xukezheng,xiangqing
                        if (!Strings.isNullOrEmpty(uitem.getZhizhao()) && uitem.getZhizhao().indexOf("//imgcdn.") <0) {
                            uitem.setZhizhao(uitem.getZhizhao().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        if (!Strings.isNullOrEmpty(uitem.getXukezheng()) && uitem.getXukezheng().indexOf("//imgcdn.") <0) {
                            uitem.setXukezheng(uitem.getXukezheng().replace("//img.", "//imgcdn."));
                            ug =true;
                        }
                        if (!Strings.isNullOrEmpty(uitem.getXiangqing())) {
                            uitem.setXiangqing(uitem.getXiangqing().replace("//img.", "//imgcdn."));
                            ug =true;
                        }

                        if (!ug) continue;

                        uitem.updateById();
                        logger.info("==============================storestoCdn uitem.updateById() ok uindex=" + uindex);
                    }
                    uflag = upage != null && upage.getRecords().size() == limit;
                    uindex++;
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========storestoCdn flag=" + flag);
            logger.info("==========storestoCdn index=" + index);
        }
    }

//    @Scheduled(cron = "0 13 18 * * ?")
    public void bannertoCdn() {

        Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>()
                .setSqlSelect("id,mcode,mpcode,state,iscdn")
                .eq("iscdn", 1);

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;

        while (flag) {
            Page<MerchantApp> page = merchantAppService.selectPage(new Page<MerchantApp>(index, limit), wrapper);
            for (MerchantApp mapp : page.getRecords()) {

                Wrapper<Banner> uwrapper = new EntityWrapper<Banner>().setSqlSelect("id,pic").eq("mpid", mapp.getId());

                boolean uflag = true;
                Integer uindex = 1;

                while (uflag) {
                    logger.info("==============================bannertoCdn 3333");

                    Page<Banner> upage = bannerService.selectPage(new Page<Banner>(uindex, limit), uwrapper);
                    for (Banner uitem : upage.getRecords()) {
                        logger.info("==============================bannertoCdn 4444");

                        if (Strings.isNullOrEmpty(uitem.getPic())) continue;
                        if (uitem.getPic().indexOf("//imgcdn.") > 0) continue;

                        uitem.setPic(uitem.getPic().replace("//img.", "//imgcdn."));
                        uitem.updateById();
                        logger.info("==============================bannertoCdn uitem.updateById() ok uindex=" + uindex);
//                        break;
                    }
                    uflag = upage != null && upage.getRecords().size() == limit;
                    uindex++;
                }
//                break;
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========bannertoCdn flag=" + flag);
            logger.info("==========bannertoCdn index=" + index);
        }
    }

//    @Scheduled(cron = "0 58 16 * * ?")
    public void userTouxiangCdn() {

        Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>().setSqlSelect("id,mcode,mpcode,state,iscdn").eq("id", 30);
        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
//            Page<MerchantApp> page = merchantAppService.selectPage(new Page<MerchantApp>(index, limit), wrapper);
            Page<MerchantApp> page = merchantAppService.selectPage(new Page<MerchantApp>(index, limit), wrapper);
            for (MerchantApp mapp : page.getRecords()) {
                logger.info("==============================userTouxiangCdn 11111");

                Wrapper<User> uwrapper = new EntityWrapper<User>().setSqlSelect("id,avatar_pic avatarPic,openid,mpid")
                        .isNotNull("openid").eq("mpid", 30);
//                        .isNotNull("openid").eq("mpid", mapp.getId());

                logger.info("==============================userTouxiangCdn 2222");

                String mcode = mapp.getMcode() + "/" + mapp.getMpcode() + "/0avatar/";
                logger.info("==============================userTouxiangCdn 22221111");

                String uppath = mapp.getIscdn() == 1 ? Constants.IMG_UPLOAD_PATH + "0cdn/" : Constants.IMG_UPLOAD_PATH;
                logger.info("==============================userTouxiangCdn 22222222");

                uppath = uppath + mcode;
                String host = mapp.getIscdn().intValue() == 1 ? Constants.IMG_UPLOAD_HOST.replace("img.", "imgcdn.") : Constants.IMG_UPLOAD_HOST;

                logger.info("==============================userTouxiangCdn uppath=" + uppath);
                HttpUtil.checkDirectory(uppath);
                logger.info("==============================userTouxiangCdn 22223333");

                Integer uindex = 1;
                boolean uflag = true;
                boolean err = false;
                HttpClient httpclient = HttpClients.createDefault();

                while (uflag) {
                    logger.info("==============================userTouxiangCdn 3333");

                    Page<User> upage = userService.selectPage(new Page<User>(uindex, limit), uwrapper);
                    for (User uitem : upage.getRecords()) {
                        logger.info("==============================userTouxiangCdn 4444");

                        if (Strings.isNullOrEmpty(uitem.getAvatarPic())) continue;

                        logger.info("==============================userTouxiangCdn 5555");
                        String txpath = null;

                        if (!uitem.getAvatarPic().startsWith("https://wx.qlogo.cn")) continue;
                        try {

                            HttpGet httpget = new HttpGet(uitem.getAvatarPic());
                            HttpResponse response = httpclient.execute(httpget);

                            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                                String content = "httpGet failed,url:" + uitem.getAvatarPic() + ",http StatusCode:" + response.getStatusLine().getStatusCode();
                                logger.error(content);
                                continue;
                            } else if (response.getFirstHeader("X-ErrNo") != null) {

                                logger.info("------------------response.getFirstHeader(X-ErrNo)=" + response.getFirstHeader("X-ErrNo"));
                                JSONObject json = WeixinUtil.getWXUserInfo(uitem.getOpenid(), uitem.getMpid().toString());
                                logger.info("------------------json=" + JSON.toJSONString(json));

                                if (json.containsKey("avatarUrl")) {
                                    uitem.setAvatarPic(json.getString("avatarUrl"));
                                    uitem.updateById();
                                }
                                continue;
                            }

                            String ul = uitem.getAvatarPic();
                            String imgname = EncryptUtil.md5(ul) + ".jpg";
                            txpath = uppath + imgname;

                            err = false;
                            int byteread = 0;
                            int bytesum = 0;


                            logger.debug(">>>>>> downloadFile start and ul=" + ul);
                            URL url = new URL(ul);
                            File file = new File(txpath);
                            if (file.exists()) {
                                file.delete();
                                file = new File(txpath);
                            }

                            URLConnection conn = url.openConnection();
                            InputStream inStream = conn.getInputStream();
                            FileOutputStream fs = new FileOutputStream(txpath);

                            byte[] buffer = new byte[1204];
                            while ((byteread = inStream.read(buffer)) != -1) {
                                bytesum += byteread;
                                fs.write(buffer, 0, byteread);
                            }
                            logger.debug(">>>>>> downloadFile OK and targetFile=" + txpath);

                        } catch (FileNotFoundException e) {
                            logger.error("FileNotFoundException", e);
                            err = true;
                        } catch (IOException e) {
                            logger.error("IOException", e);
                            err = true;
                        }

                        if (!err) {
                            txpath = mapp.getIscdn() == 1 ? txpath.replace("/fafa/www/images/0cdn/", Constants.IMG_UPLOAD_HOST.replace("//img.", "//imgcdn."))
                                    : txpath.replace("/fafa/www/images/", Constants.IMG_UPLOAD_HOST);
                            uitem.setAvatarPic(txpath);
                            uitem.updateById();
                            logger.info("==============================userTouxiangCdn uitem.updateById() ok uindex=" + uindex);
                        }
                        break;
                    }
                    uflag = upage != null && upage.getRecords().size() == limit;
                    uindex++;
                }
                break;
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========userTouxiangCdn flag=" + flag);
            logger.info("==========userTouxiangCdn index=" + index);

        }


    }

}
